package com.valor.order.controller;

import com.valor.order.converter.OrderFormToOrderDTO;
import com.valor.order.dto.OrderDTO;
import com.valor.order.enums.ResultEnum;
import com.valor.order.exception.OrderException;
import com.valor.order.form.OrderForm;
import com.valor.order.service.OrderService;
import com.valor.order.utils.ResultVOUtil;
import com.valor.order.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Map;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;

    @PostMapping
    public ResultVO create(@Valid OrderForm orderForm, BindingResult result, Map<String,Object> map){

        if (result.hasErrors()){
          log.error("创建订单参数不正确,orderForm={}",orderForm);
          throw new OrderException(ResultEnum.PARAM_ERROR.getCode(),
                                   result.getFieldError().getDefaultMessage());
        }
        OrderDTO orderDTO = OrderFormToOrderDTO.convert(orderForm);
        if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())){
            log.error("【创建订单】购物车为空");
            throw new OrderException(ResultEnum.CART_EMPTY);
        }
        OrderDTO orderResult = orderService.create(orderDTO);
       map.put("orderId"，orderResult.getOrderId());
       return ResultVOUtil.success(map);
    }
}
